package com.heima.behavior.service.impl;

import com.heima.behavior.dto.BehaviorDto;
import com.heima.behavior.dto.UpdateArticleMessageDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApBehaviorService;
import com.heima.behavior.service.IApLikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP点赞行为表 服务实现类
 * </p>
 *
 * @author Wq
 * @since 2022-10-18
 */
@Service
public class ApLikesBehaviorServiceImpl implements IApLikesBehaviorService {

    @Autowired
    private IApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IApBehaviorService apBehaviorService;

    @Override
    public ResponseResult saveApLikes(BehaviorDto dto) {
        //生成EntryId
        ApBehaviorEntry entry = apBehaviorEntryService.getEntryByUserId(dto.getUserId());
        //参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //组装数据
        ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
        apLikesBehavior.setEntryId(entry.getId());
        apLikesBehavior.setArticleId(dto.getArticleId());
        apLikesBehavior.setType(0);
        apLikesBehavior.setOperation(dto.getOperation());
        apLikesBehavior.setCreatedTime(new Date());
        //保存到数据库
        mongoTemplate.save(apLikesBehavior);
        //保存kafka
        UpdateArticleMessageDto articleMessage = new UpdateArticleMessageDto();
        articleMessage.setType(0);
        articleMessage.setArticleId(dto.getArticleId());
        articleMessage.setAdd(dto.getOperation() == 0 ? 1 : -1);
        //使用多线程异步往kafka发送
        apBehaviorService.sendBehaviorMessageToKafka(articleMessage);
        return ResponseResult.okResult();
    }


}
